package cn.reyuxi.simple

import android.view.View
import cn.reyuxi.emptyview.EmptyContentView
import cn.reyuxi.emptyview.EmptyView
import cn.reyuxi.emptyview.EmptyViewType
import cn.reyuxi.emptyview.EmptyViewTypeDef
import cn.reyuxi.emptyview.VisibilityHandler

class SimpleEmptyView private constructor() : EmptyView {
    private var shownContentType: Int = EmptyViewType.NO_DATA
    private lateinit var bindView: View
    private var emptyShown = false
    private var emptyContentView: EmptyContentView? = null
    private var visibilityHandler: VisibilityHandler? = null
    private var onClickListener: View.OnClickListener? = null

    companion object {
        fun setup(block: () -> Configure): Configure {
            return block.invoke()
        }
    }

    override fun bindTo(v: View) {
        if (emptyShown) {
            hide()
        }
        bindView = v
    }

    override fun setContentView(emptyContentView: EmptyContentView) {
        this.emptyContentView = emptyContentView
    }

    override fun setVisibilityHandler(visibilityHandler: VisibilityHandler) {
        this.visibilityHandler = visibilityHandler
    }

    override fun setOnClickListener(listener: View.OnClickListener?) {
        onClickListener=listener
    }

    override fun show(@EmptyViewTypeDef type: Int) {
        val typeChanged = this.shownContentType != type
        if (typeChanged) {
            hide()
            shownContentType = type
        }
        handleVisibility(shownContentType, true)
    }

    override fun hide() {
        handleVisibility(shownContentType, false)
    }

    override fun isShown(): Boolean {
        return emptyShown
    }

    override fun getEmptyContentView(): EmptyContentView? {
        return emptyContentView
    }

    override fun release() {
        hide()
        emptyContentView = null
    }

    private fun handleVisibility(type: Int, isShow: Boolean) {
        if (isShow && emptyShown) return
        val emptyView = emptyContentView?.getView(type) ?: return
        if (isShow) {
            emptyView.setOnClickListener {
                onClickListener?.onClick(it)
            }
            visibilityHandler?.onShow(emptyView, bindView)
        } else {
            visibilityHandler?.onHide()
            emptyView.setOnClickListener(null)
        }

        emptyShown = isShow
    }

    class Configure(
        val emptyView: EmptyContentView,
        val visibleHandler: VisibilityHandler
    ) {

        fun done(): EmptyView {
            return SimpleEmptyView().apply {
                setContentView(emptyView)
                setVisibilityHandler(visibleHandler)
            }
        }

        fun bindTo(v: View): EmptyView {
            return done().also {
                it.bindTo(v)
            }
        }
    }
}